<?php
/**
* @file $Id: upgrade.php 53 2006-07-10 10:25:57Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

session_start();
if(!$_SESSION['USERNAME'])
	$_SESSION['USERNAME'] = 'upgrade';
$_FOCUS['User'] = array('PROFILE'=>'admin');
$_FOCUS['Preferences']['Preferences'] = array('PROFILE'=>'admin');
$_FOCUS['SystemPreferences']['system'] = $_FOCUS['SystemPreferences']['Preferences'] = array(true);

require_once('Warehouse.php');
ini_set('max_execution_time',0);
error_reporting(~E_WARNING && ~E_NOTICE);
Warehouse('header');
echo '<BODY background=assets/bg.gif>';
echo DrawPNG('themes/'.Preferences('THEME').'/logo.png','border=0 width=154 height=34');
DrawHeader('Focus/SIS Installation');

if(!function_exists('pg_connect'))
{
	$error[] = 'Your version of PHP does not include PostgreSQL support.  <UL><LI>If you\'ve install Focus/SIS on a Mac OS X machine, download and install the PHP and PostgreSQL packages from Marc Liyanage\'s <A HREF=http://www.entropy.ch>Entropy.ch</A> site.  <LI>If using Windows, open the php.ini file in a text editor like WordPad and remove the semi-colon before the line ";pg_sql.dll."<LI> If you\'re using a Linux or Unix server, you\'ll probably need to recompile PHP using the --with-pgsql option.</UL>';
	echo ErrorMessage($error,'error');
	Warehouse('footer');
	exit;
}
else
{
	if($DatabaseServer!='localhost')
		$connectstring = "host=$DatabaseServer ";
	$connectstring .= "port=$DatabasePort dbname=$DatabaseName user=$DatabaseUsername";
	if(!empty($DatabasePassword))
		$connectstring.=" password=$DatabasePassword";
	if($connection = pg_connect($connectstring))
	{}
	else
	{
		if($DatabaseServer!='localhost')
			$connectstring = "host=$DatabaseServer port=$DatabasePort ";
		$connectstring .= "dbname=$DatabaseName user=$DatabaseUsername";
		if(!empty($DatabasePassword))
			$connectstring.=" password=$DatabasePassword";
		if($connection = pg_connect($connectstring))
		{}
		else
		{
			$connectstring = "host=$DatabaseServer port=$DatabasePort ";
			$connectstring .= "dbname=$DatabaseName user=$DatabaseUsername";
			if(!empty($DatabasePassword))
				$connectstring.=" password=$DatabasePassword";
			$connection = pg_connect($connectstring);
		}
	}

	if(!$connection)
		$error[] = 'Focus/SIS cannot connect to the Postgres database.  Either the database "'.$DatabaseName.'" does not exist, Postgres is not running, it was not started with the -i option, or connections from this host are not allowed in the pg_hba.conf file. <BR><BR> If the database does not exist, create it using phpPGAdmin, PGAdmin III, or by opening a terminal window and following these directions:<OL>
	<LI>Login as the postgres user<BR>
		ex) server$ su - postgres
	<LI>Login to the postgres database server using the template1 database<BR>
		ex) server$ psql template1
	<LI>Create the focus database<BR>
		ex) template1=# CREATE DATABASE focus;
';

}

if(!count($error))
{
	$result = @pg_exec($connection,'SELECT * FROM CONFIG');
	if($result!==false)
	{
		$error[] = 'You\'ve already run the installation script.';
	
		echo ErrorMessage($error,'error');
		Warehouse('footer');
		exit;
	}
}

if(count($error))
{
	echo ErrorMessage($error,'error');
}
else
{
	// TAKEN FROM OSCOMMERCE INSTALL
	$FP = fopen($staticpath.'/install.sql','rb');
	$restore_query = fread($FP,filesize($staticpath.'/install.sql'));
	fclose($FP);
	
	$sql_array = array();
	$sql_length = strlen($restore_query);
	$pos = strpos($restore_query, ';');
	for ($i=$pos; $i<$sql_length; $i++) {
	if ($restore_query[0] == '-' && $restore_query[1] == '-') {
	  $restore_query = ltrim(substr($restore_query, strpos($restore_query, "\n")));
	  $sql_length = strlen($restore_query);
	  $i = strpos($restore_query, ';')-1;
	  continue;
	}
	if ($restore_query[($i+1)] == "\n") {
	  for ($j=($i+2); $j<$sql_length; $j++) {
		if (trim($restore_query[$j]) != '') {
		  $next = substr($restore_query, $j, 6);
		  if ($next[0] == '-' && $next[1] == '-') {
	// find out where the break position is so we can remove this line (#comment line)
			for ($k=$j; $k<$sql_length; $k++) {
			  if ($restore_query[$k] == "\n") break;
			}
			$query = substr($restore_query, 0, $i+1);
			$restore_query = substr($restore_query, $k);
	// join the query before the comment appeared, with the rest of the dump
			$restore_query = $query . $restore_query;
			$sql_length = strlen($restore_query);
			$i = strpos($restore_query, ';')-1;
			continue 2;
		  }
		  break;
		}
	  }
	  if ($next == '') { // get the last insert query
		$next = 'insert';
	  }
	  if ( (eregi('create', $next)) || (eregi('insert', $next)) || (eregi('drop t', $next)) ) {
		$next = '';
		$sql_array[] = substr($restore_query, 0, $i);
		$restore_query = ltrim(substr($restore_query, $i+1));
		$sql_length = strlen($restore_query);
		$i = strpos($restore_query, ';')-1;
	  }
	}
	}
	
	for ($i=0; $i<sizeof($sql_array); $i++) {
	DBQuery($sql_array[$i]);
	}
	// END OSCOMMERCE SECTION
	
	
	$result = @pg_exec($connection,'SELECT * FROM CONFIG');
	if($result===false)
		$errstring = pg_last_error($connection);
	
	if(strpos($errstring,'config: permission denied')!==false)
		$error[] = 'The database was created with the wrong permissions.  The user specified in the config.inc.php file does not have permission to access the Focus/SIS database.  Use the super-user (postgres) or recreate the database adding \connect - YOUR_USERNAME to the top of the install.sql file.';
	elseif(strpos($errstring,'elation "config" does not exist')!==false)
		$error[] = 'At least one of the tables does not exist.  Make sure you ran the focus.sql file as described in the INSTALL file.';
	elseif($errstring)
		$error[] = $errstring;

	DBQuery("VACUUM");
	DBQuery("ANALYZE");

	$_SESSION['USERNAME'] = 'admin';
	PopTable('header','Congratulations');
	echo '<H3>You\'ve successfully installed Focus/SIS</H3>';
	echo '<A HREF=index.php>Click here to continue.</A><BR>Login using the username "admin" and password "admin."';
	PopTable('footer');
}
Warehouse('footer');
?>
